import mysql2 from "mysql2"
import { GetConnection, GetResult } from "../../util/db.js"
import { JoinSQLInsertKeys } from "../../util/JoinSQL.js"
import MenuModel from "../../model/menuModel/menuModel.js"

class MenuService {
    /**
     * 获取全部菜单
     * @param {boolean} isAdmin
     * @returns {Promise<mysql2.RowDataPacket[] | mysql2.RowDataPacket[][]>}
     */
    static async GetMenuList(isAdmin) {
        try {
            const conn = await GetConnection()
            let sql = ''
            if (isAdmin) {
                sql = `
select *
from menutable
order by sequence
            `
            } else {
                sql = `
SELECT *
FROM menutable a
WHERE NOT EXISTS (
    SELECT 1 FROM menuRights b WHERE a.id = b.menuID AND rightsCode IN ('admin')
)
ORDER BY sequence;
            `
            }
            const { rows: result, fields } = await GetResult(sql, undefined, conn)
            return result
        } catch (error) {
            return Promise.reject(error)
        }
    }

    /**
     * 返回菜单目录，树结构
     * @returns {Promise<mysql2.RowDataPacket[] | mysql2.RowDataPacket[][]>}
     */
    static async GetMenuRootList() {
        try {
            const conn = await GetConnection()
            let sql = `select * from menutable where type = 1`
            const { rows, fields } = await GetResult(sql, undefined, conn)
            return rows
        } catch (error) {
            return Promise.reject(error)
        }
    }

    /**
     * @param {} condition
     * @returns {Promise<boolean>}
     */
    static async InsertMenu(condition) {
        try {
            const conn = await GetConnection()
            const model = new MenuModel(condition)
            const { keys, values } = model.GetKeys_Values()
            let sql = `
insert into menutable 
            `
            sql += JoinSQLInsertKeys(keys)
            const { rows: result, fields } = await GetResult(sql, [[values]], conn, true)
            return result && result.affectedRows
        } catch (error) {
            return Promise.reject(error)
        }
    }

    /**
     * @param {string} id 
     */
    static async DeleteMenu(id) {
        try {
            const conn = await GetConnection()
            let sql = "delete from menutable where id = ?"
            const { rows } = await GetResult(sql, [id], conn, true)
            return rows && rows.affectedRows
        } catch (error) {
            return Promise.reject(error)
        }
    }

    /**
     * 修改menu
     * @param {*} condition
     * @returns {Promise<boolean>}
     */
    static async UpdateMenu(condition) {
        try {
            let conn = await GetConnection()
            let model = new MenuModel(condition)
            let sql = 'update menutable set '
            let { rows } = await GetResult(sql, _, conn, true)
            return rows || rows.affectedRows
        } catch (error) {
            return Promise.reject(error)
        }
    }
}

export default MenuService